package com.hundsun.yr.universal.p2p.presenter.impl;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.data.HSSharedPreferences;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils;
import com.hundsun.yr.universal.library.widget.HSToast;
import com.hundsun.yr.universal.p2p.bean.AdSlideBeen;
import com.hundsun.yr.universal.p2p.bean.MyInvestBeen;
import com.hundsun.yr.universal.p2p.bean.MyLoanListBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Config;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.interactor.base.RequestInteractor;
import com.hundsun.yr.universal.p2p.interactor.impl.StringRequestGetInteractorImpl;
import com.hundsun.yr.universal.p2p.interactor.impl.StringRequestInteractorImpl;
import com.hundsun.yr.universal.p2p.listener.BaseMultiLoadedListener;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.utils.AndroidDes3Util;
import com.hundsun.yr.universal.p2p.utils.GsonTool;
import com.hundsun.yr.universal.p2p.utils.Logs;
import com.hundsun.yr.universal.p2p.view.base.BaseListView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import de.greenrobot.event.EventBus;


/**
 * @Title: WaitPayListPresenterImpl.java 
 * @Description: TODO(用一句话描述该文件做什么) 
 * @date 2015-10-27 上午11:18:59 
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com 
 * @replace author:
 * @replace date:
 * @version V1.0   
 */
public class WaitPayListPresenterImpl implements RequestPresenter,BaseMultiLoadedListener<String>,OnClickListener{
	
	private Context mContext = null;
	private BaseListView mBaseView = null;
	private RequestInteractor mInteractor=null;
	private RequestInteractor mInteractor2=null;
	/**list的key**/
	private String mKey;
	/**任务名**/
	private String mTask_name;
	/**请求地址**/
	private String mUrl;
	/**加载事件**/
	private int mEvent_tag;
	/**参数**/
	private HashMap<String, String> mParams;
	/**是否刷新**/
	private boolean mIsSwipeRefresh;
	/**用户信息sp文件**/
	private HSSharedPreferences sharedPreferences = null;
	
	public WaitPayListPresenterImpl(Context context,BaseListView baseView,String key) {
		// TODO Auto-generated constructor stub
		if (null == baseView) {
            throw new IllegalArgumentException("Constructor's parameters must not be Null");
        }
		this.mContext=context;
		this.mBaseView=baseView;
		this.mInteractor =new StringRequestInteractorImpl(this);
		this.mInteractor2 =new StringRequestGetInteractorImpl(this);
		this.mKey=key;
		this.sharedPreferences = new HSSharedPreferences(context, Config.SPPath.file_userLoginedInfo);
	}

	@Override
	public void onSuccess(String task_name,int event_tag, String data) {
		//网络请求成功，进度条消失
		Logs.e("data wait:77777 " + data);
		mBaseView.hideLoading();
		mBaseView.closeProgress();//请求数据成功
		try{
			AdSlideBeen adSlideBeen = (AdSlideBeen) GsonTool.getInstanceByJson(AdSlideBeen.class, data);
			if (adSlideBeen.code.equals(Constants.REQUESTCODE_100600)){
				sharedPreferences.putBoolean(UserInfo.ISLOGIN, false);
				EventBus.getDefault().post(new EventCenter(Constants.EVENT_DATA_LOGIN_EXPIRED));
			}
			switch (task_name){
				case TaskConstants.INVERST_LIST://我的投资列表
					switch (adSlideBeen.code){
						case Constants.REQUESTCODE_000000:
							//请求成功，对数据进行解密
							try {
								String decode = AndroidDes3Util.decode(adSlideBeen.data, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0,24), (Date.parse(adSlideBeen.timestamp)+"").substring(0,8));
								String[] split = decode.split("\\n");
								ArrayList<MyInvestBeen> invests = GsonTool.jsonToArrayList(split[1], MyInvestBeen.class);

								//对数据进行解析
								if (event_tag==Constants.EVENT_REFRESH_DATA){
									//event_tag为刷新界面
									if (invests.size() > 0){
										mBaseView.refreshListData(invests);

									}else {
										mBaseView.refreshListData(null);
										//没有数据显示空页面
										mBaseView.showEmpty(0, mContext.getString(R.string.empty_msg), this);
									}
								}else if (event_tag == Constants.EVENT_LOAD_MORE_DATA){
									mBaseView.addMoreListData(invests);
								}
							} catch (Exception e) {
								new HSToast(mContext).showToast(mContext.getString(R.string.date_error));
								e.printStackTrace();
							}
							break;
						case Constants.REQUESTCODE_100600:
							mBaseView.onFailure(TaskConstants.INVERST_LIST);
							new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
							break;
						case Constants.REQUESTCODE_100020:
							mBaseView.onFailure(TaskConstants.INVERST_LIST);
							//Header值为空--不做任何提示
							break;
						case Constants.REQUESTCODE_100010:
							mBaseView.onFailure(TaskConstants.INVERST_LIST);
							break;
						default:
							new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
							mBaseView.onFailure(TaskConstants.INVERST_LIST);
							mBaseView.showError(adSlideBeen.msg, this);
							break;
					}
					break;

				case TaskConstants.LOAN_LIST://我的借款列表
					switch (adSlideBeen.code){
						case Constants.REQUESTCODE_000000:
							//请求成功，对数据进行解密
							try {
								String decode = AndroidDes3Util.decode(adSlideBeen.data, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0,24), (Date.parse(adSlideBeen.timestamp)+"").substring(0,8));
								String[] split = decode.split("\\n");
								ArrayList<MyLoanListBeen> loanLists = GsonTool.jsonToArrayList(split[1],MyLoanListBeen.class);

								Logs.e("LOAN_LIST:77777 " + split[1]);
								//对数据进行解析
								if (event_tag==Constants.EVENT_REFRESH_DATA){
									//event_tag为刷新界面
									if (loanLists.size() > 0){
										mBaseView.refreshListData(loanLists);
									}else {
										mBaseView.refreshListData(null);
										//没有数据显示空页面
										mBaseView.showEmpty(0, mContext.getString(R.string.empty_msg), this);
									}
								} else if (event_tag == Constants.EVENT_LOAD_MORE_DATA){
									mBaseView.addMoreListData(loanLists);
								}
							} catch (Exception e) {
								new HSToast(mContext).showToast(mContext.getString(R.string.date_error));
								e.printStackTrace();
							}
							break;
						case Constants.REQUESTCODE_100600:
							mBaseView.onFailure(TaskConstants.LOAN_LIST);
							new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
							break;
						case Constants.REQUESTCODE_100020:
							mBaseView.onFailure(TaskConstants.LOAN_LIST);
							//Header值为空--不做任何提示
							break;
						default:
							mBaseView.onFailure(TaskConstants.LOAN_LIST);
							new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
							mBaseView.showError(adSlideBeen.msg, this);
							break;
					}
					break;

				case TaskConstants.TASK_APPLYCANCEL://借款撤销
					switch (adSlideBeen.code){
						case Constants.REQUESTCODE_000000:
							//请求成功，对数据进行解密
							try {
								String decode = AndroidDes3Util.decode(adSlideBeen.data, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0,24), (Date.parse(adSlideBeen.timestamp)+"").substring(0,8));
								String[] split = decode.split("\\n");
								mBaseView.initializeViews(TaskConstants.TASK_APPLYCANCEL,"");
							} catch (Exception e) {
								new HSToast(mContext).showToast(mContext.getString(R.string.date_error));
								e.printStackTrace();
							}
							break;
						case Constants.REQUESTCODE_100500:
							new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.login_overdue)).show();
							break;
						case Constants.REQUESTCODE_100020:
							//Header值为空--不做任何提示
							break;
						default:
							new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
							break;
					}
					break;

				case TaskConstants.TASK_PAYUPORDER://去支付
					switch (adSlideBeen.code){
						case Constants.REQUESTCODE_000000:
							//请求成功，对数据进行解密
							try {
								String decode = AndroidDes3Util.decode(adSlideBeen.data, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0,24), (Date.parse(adSlideBeen.timestamp)+"").substring(0,8));
								mBaseView.initializeViews(TaskConstants.TASK_PAYUPORDER,decode.substring(decode.indexOf("<")));
							} catch (Exception e) {
								new HSToast(mContext).showToast(mContext.getString(R.string.date_error));
								e.printStackTrace();
							}
							break;
						case Constants.REQUESTCODE_100500:
							new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.login_overdue)).show();
							break;
						case Constants.REQUESTCODE_100020:
							//Header值为空--不做任何提示
							break;
						default:
							new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
							break;
					}
					break;

				case TaskConstants.TASK_BIDCANCEL:
					switch (adSlideBeen.code){
						case Constants.REQUESTCODE_000000:
							//请求成功，对数据进行解密
							try {
								String decode = AndroidDes3Util.decode(adSlideBeen.data, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0,24), (Date.parse(adSlideBeen.timestamp)+"").substring(0,8));
								String[] split = decode.split("\\n");
								mBaseView.initializeViews(TaskConstants.TASK_BIDCANCEL,split[1]);
							} catch (Exception e) {
								new HSToast(mContext).showToast(mContext.getString(R.string.date_error));
								e.printStackTrace();
							}
							break;
						case Constants.REQUESTCODE_100500:
							new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.login_overdue)).show();
							break;
						case Constants.REQUESTCODE_100020:
							//Header值为空--不做任何提示
							break;
						default:
							new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
							break;
					}
					break;
			}
		} catch (Exception e){
			new HSToast(mContext).showToast(mContext.getString(R.string.date_error));
			e.printStackTrace();
		}
	}

	@Override
	public void onException(String task_name,String msg) {
		// TODO Auto-generated method stub
		if (TextUtils.equals(task_name,TaskConstants.LOAN_LIST) || TextUtils.equals(task_name,TaskConstants.INVERST_LIST)) {
			mBaseView.closeProgress();
			mBaseView.hideLoading();
			mBaseView.showError(msg, this);
			mBaseView.onFailure(task_name);
		}
	}

	
	@Override
	public void loadingData(String task_name, String url, int event_tag,
			HashMap<String, String> params, boolean isSwipeRefresh) {
		// TODO Auto-generated method stub
        
		if(event_tag==Constants.EVENT_REFRESH_DATA){
			this.mTask_name=task_name;
			this.mUrl=url;
			this.mParams=params;
			this.mIsSwipeRefresh=isSwipeRefresh;
			this.mEvent_tag=event_tag;
		}


		mBaseView.hideLoading();

        if(event_tag==Constants.EVENT_PROGRESS){
        	mBaseView.showProgress("");
		}
        if (isSwipeRefresh) {
        	mBaseView.showLoading(mContext.getString(R.string.common_loading_message));
        }
		if (NetUtils.isNetworkConnected(mContext)) {
			if (TextUtils.equals(task_name, TaskConstants.INVERST_LIST)){
				mInteractor2.getRequestData(task_name, url, event_tag, params);
			} else if (TextUtils.equals(task_name,TaskConstants.LOAN_LIST)){
				mInteractor2.getRequestData(task_name,url,event_tag,params);
			}
        }else{
			mBaseView.closeProgress();
        	mBaseView.hideLoading();
        	mBaseView.showNetError(this);
        	mBaseView.onFailure(task_name);
        }
	}

	@Override
	public void loadingData(String task_name, String url, int event_tag, HashMap<String, String> params, HashMap<String, String> header, boolean isSwipeRefresh) {

	}

	/**
	 * json+header
	 * @param task_name
	 * @param url
	 * @param event_tag
	 * @param params
	 * @param header
     * @param isSwipeRefresh
     */
	@Override
	public void loadingData(String task_name, String url, int event_tag, JSONObject params, HashMap<String, String> header, boolean isSwipeRefresh) {
		if (NetUtils.isNetworkConnected(mContext)) {
			if (isSwipeRefresh) {
				mBaseView.showProgress("");
			}
			mInteractor.getRequestData(task_name, url, event_tag, params, header);
		} else {
			mBaseView.closeProgress();
			new HSToast(mContext).showToast(R.string.common_no_network);
			mBaseView.showNetError(this);
		}
	}

	@Override
	public void initialized() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onClick(View v) {
		if (TextUtils.equals(mTask_name,TaskConstants.INVERST_LIST) || TextUtils.equals(mTask_name,TaskConstants.LOAN_LIST)){
			loadingData(mTask_name, mUrl, mEvent_tag, mParams, mIsSwipeRefresh);
		}
	}

}
